package com.example.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ItemListMainAdapter.caa{

    private ListView mainListview;
        String URl;
        List<top>list;
        List<TopBean.ResultBean.DataBean>beanList;
        ItemListMainAdapter adapter;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1) {
                String json=(String)msg.obj;
                Gson gson=new Gson();
                TopBean topBean=gson.fromJson(json,TopBean.class);
                beanList=topBean.getResult().getData();
                addDataForList(beanList);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        URl =  URLutils.getUrl("top");
        loadData();

    }
    private void addDataForList(List<TopBean.ResultBean.DataBean>beanList) {
        list=new ArrayList<>();
        for (int i = 0; i < beanList.size(); i++) {
            top top = new top(beanList.get(i).getTitle(),beanList.get(i).getThumbnail_pic_s(),beanList.get(i).getThumbnail_pic_s02()
            ,beanList.get(i).getThumbnail_pic_s03(),beanList.get(i).getDate(),beanList.get(i).getAuthor_name());
            list.add(top);
        }
        adapter=new ItemListMainAdapter(this,list,this);
        mainListview.setAdapter(adapter);
    }

    public void  loadData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //执行网络请求
                String json= HttpUtils.getJsonByNetwork(URl);
                //将子线程获取到的数据，通过handle对象传递到主线程
                Message msg=handler.obtainMessage();
                msg.what=1;
                msg.obj=json;
                handler.sendMessage(msg);
            }
        }).start();
    }
    private void initView() {
        mainListview = (ListView) findViewById(R.id.main_listview);
    }

    @Override
    public void chage(int postion) {
        list.remove(postion);
        adapter.notifyDataSetChanged();
    }
}
